﻿using System;
using System.Collections.Generic;
using System.Web;
using System.IO;
using System.Text.RegularExpressions;


namespace CCPSIP.Sticker
{
    /// <summary>CCPSIP_027：贈送禮物貼圖 API</summary>
    /// idHeader = 裝置 UUID 前八碼。
    /// checkcode = 裝置限時驗證碼。
    /// StickerID = 貼圖ID，目前為資料夾名稱。
    /// Recipient = 受贈貼圖的帳號。

    public class gift_send : IHttpHandler
    {
        private const string kStickerDirDefault = @"\\192.168.19.1\Sticker_Default\Default";
        private const string kStickerRootDir = @"\\192.168.19.1\iSender_D";
        private const string kWinUserId = "ccpsip_cloud";
        private static byte[] kWinUserKey = { 0x59, 0x4C, 0x43, 0x71, 0x6A,
                                          0x6D, 0x44, 0x6A, 0x32, 0x5A,
                                          0x72, 0x62, 0x72, 0x43, 0x39,
                                          0x68, 0x51, 0x6E, 0x63, 0x6B,
                                          0x57, 0x32, 0x64, 0x74, 0x62
                                        };
        private const string kGiftRootDir = @"\\192.168.19.1\iSender_D\Gift";


        public void ProcessRequest(HttpContext context)
        {
            HttpRequest req = context.Request;
            HttpResponse resp = context.Response;
            resp.ContentType = "text/plain";
            resp.ContentEncoding = System.Text.Encoding.UTF8;
            DateTime reqTime = DateTime.Now;
            string resultStr = "";


            try
            {
                //【01】取得POST參數，驗證身分
                //
                string idHeader = req.Form["idHeader"];
                string checkcode = req.Form["checkcode"];
                string StickerID = req.Form["StickerID"];//貼圖ID，目前為資料夾名稱
                string Recipient = req.Form["Recipient"];//受贈貼圖的帳號

                SipUserInfo userInfo = SipKit.GetUserInfo(idHeader, checkcode, req);
                if (userInfo == null)
                {
                    throw new Exception("Error_01: Cannot identify this device");//無法識別此裝置
                }


                //【02】檢查檔案路徑問題(防路徑攻擊)
                //
                if (StickerID.IndexOfAny(Path.GetInvalidFileNameChars()) >= 0
                  || string.IsNullOrEmpty(StickerID))
                {
                    throw new Exception("Error_02: Directory Name Error");//資料夾名稱錯誤
                }
                else if (!OracleKitUser.hasUser(Recipient))
                {
                    throw new Exception("Error_03: Recipient Error");//受贈者錯誤
                }


                //【03】組合路徑
                //
                string userDirName = userInfo.SIP_Num;
                if (SipKit.isHQMobileExt(userInfo.SIP_Num))
                {
                    userDirName = SipKit.getHQDesktopExt(userInfo.SIP_Num);
                }
                string sourceDir = string.Format(@"{0}\{1}\Stickers\{2}", kStickerRootDir, userDirName, StickerID);
                string targetDir = string.Format(@"{0}\{1}\{2}\{3}", kGiftRootDir, Recipient, userInfo.SIP_Num, StickerID);


                //【04】切換網域身分存取資料夾
                //
                string tempCode = System.Text.Encoding.UTF8.GetString(kWinUserKey);

                using (new Tools.Impersonator(kWinUserId, "", tempCode))
                {
                    if (!Directory.Exists(sourceDir))
                    {
                        sourceDir = string.Format(@"{0}\{1}", kStickerDirDefault, StickerID);
                        if (Directory.Exists(sourceDir))
                            throw new Exception("Error_04: Cannot send default sticker");//不能贈送預設貼圖
                        else
                            throw new Exception("Error_05: Directory not found");//資料夾不存在
                    }

                    //【05-1】把禮物貼圖複製到暫存區
                    //
                    string[] sFiles = Directory.GetFiles(sourceDir, "*.png", SearchOption.TopDirectoryOnly);
                    if (sFiles.Length <= 0)
                    {
                        throw new Exception("Error_06: Sticker not found");//貼圖不存在
                    }

                    //【05-2】刪除重覆的舊禮物
                    //
                    if (Directory.Exists(targetDir))
                    {
                        Directory.Delete(targetDir, true);
                    }

                    //【05-3】複製貼圖檔案
                    //
                    Directory.CreateDirectory(targetDir);

                    foreach (string sFile in sFiles)
                    {
                        string targetPath = string.Format(@"{0}\{1}", targetDir, Path.GetFileName(sFile));
                        File.Copy(sFile, targetPath, false);
                    }
                }


                //【06】寫入送禮記錄
                //
                OracleKitSticker.SendStickerGift(userInfo.SIP_Num, Recipient, StickerID);


                //【98】通知Push Service
                //
                PushKit.WakePushAsync(PushKit.PushType.Msg);


                //【99】回傳OK
                //
                resultStr = "OK";
            }
            catch (Exception ex)
            {
                resp.ContentType = "application/xml";
                resultStr = ChrisKit.Ex2Xml(ex, false);
            }
            finally
            {
                int contentLength = resp.ContentEncoding.GetByteCount(resultStr);
                resp.AppendHeader("Content-Length", contentLength.ToString());
                resp.Write(resultStr);
                resp.Flush();
                resp.Close();
            }
        }


        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

    }
}
